package com.lipl.base.javaee.netty.bio;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;

import static java.util.concurrent.Executors.newCachedThreadPool;


/**
 * @Auther: 15541
 * @Date: 2020/10/30 16:07
 * @Description:
 */
public class BIOServer {

    public static void main(String[] args) throws IOException {
        // 创建一个可缓存线程池
        ExecutorService cachedThreadPool = newCachedThreadPool();

        ServerSocket serverSocket = new ServerSocket(6666);

        System.out.println("服务器启动了");

        while(true){
            final Socket socket = serverSocket.accept();
            System.out.println("连接到一个客户端！！");

            cachedThreadPool.execute(()->{
                handler(socket);
            });
        }
    }

    public static void handler(Socket socket){

        try {
            System.out.println("线程信息id="+ Thread.currentThread().getId()+"名字="+Thread.currentThread().getName());

            byte[] bytes = new byte[1024];
            InputStream inputStream = socket.getInputStream();

            while(true){
                System.out.println("线程信息id="+ Thread.currentThread().getId()+"名字="+Thread.currentThread().getName());
                int read = inputStream.read(bytes);
                if (read != -1){
                    System.out.println(new String(bytes,0,read));
                }else{
                    break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            System.out.println("关闭和client的连接");
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

